package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.behavior.service.ApArticleRelationService;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApLikesBehaviorService;
import com.heima.behavior.service.ApUnLikesBehaviorService;
import com.heima.model.behavior.dtos.ApArticleRelationDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApLikesBehavior;
import com.heima.model.behavior.pojos.ApUnlikesBehavior;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApArticleRelationServiceImpl implements ApArticleRelationService {

    @Autowired
    ApLikesBehaviorService apLikesBehaviorService;
    @Autowired
    ApUnLikesBehaviorService apUnLikesBehaviorService;
    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;
    /**
     * 查询用户文章的点赞\不喜欢
     *
     * @param dto
     * @return
     */
    @Override
    public Map findApArticleRelation(ApArticleRelationDto dto) {
        //结果预先封装
        Map resultMap=new HashMap();
        resultMap.put("islike", false);
        resultMap.put("isunlike",false );
        if (dto==null || dto.getArticleId()==null){
            return resultMap;
        }
        /**
         * 实体类型
         0终端设备
         1用户
         */
        ApBehaviorEntry behaviorEntry=null;
        if (dto.getType()==1){
            behaviorEntry=apBehaviorEntryService.findByUserIdOrEquipmentId(dto.getEntryId(),null);
        }
        if (dto.getType()==0){
            behaviorEntry=apBehaviorEntryService.findByUserIdOrEquipmentId(null,dto.getEntryId());
        }
        if (behaviorEntry==null){
            return resultMap;
        }
        resultMap.put("entryId",behaviorEntry.getId());

        //根据行为id 查找是否点赞
        ApLikesBehavior likesBehavior = apLikesBehaviorService.getOne(
                Wrappers.<ApLikesBehavior>lambdaQuery()
                        .eq(ApLikesBehavior::getArticleId, dto.getArticleId())
                        .eq(ApLikesBehavior::getEntryId, behaviorEntry.getId())
        );
        if (likesBehavior!=null && likesBehavior.getOperation()==0){
            resultMap.put("islike",true);
        }
        //根据行为id 查找是否不喜欢
        ApUnlikesBehavior unlikesBehavior = apUnLikesBehaviorService.getOne(
                Wrappers.<ApUnlikesBehavior>lambdaQuery()
                        .eq(ApUnlikesBehavior::getArticleId, dto.getArticleId())
                        .eq(ApUnlikesBehavior::getEntryId, behaviorEntry.getId())
        );
        if (unlikesBehavior!=null && unlikesBehavior.getType().intValue()==0){
            resultMap.put("isunlike",true );
        }
        return resultMap;
    }
}